
package creature;

import java.util.ArrayList;
import java.util.Date;

import processing.core.PConstants;
import processing.core.PGraphics;
import toolib.geom.Spline2D;
import toxi.geom.Vec2D;
import toxi.math.MathUtils;
import boids.SplinePath;

public class DrawnPath extends SplinePath
{
	private long					fadeDur		= 3000;
	private float					colorFade	= 1.0f;
	private long					startTime;

	private boolean				reached		= false;

	public DrawnPath(ArrayList<Vec2D> _points, float _radius)
	{
		super(_points, _radius, Spline2D.CUBIC);
	}

	public DrawnPath(float _radius)
	{
		super(_radius, Spline2D.CUBIC);
	}

	public void clear()
	{
		super.clear();
		reached = false;
		colorFade = 1.0f;
	}

	public void setReached()
	{
		if (!reached)
		{
			startTime = new Date().getTime();
		}
		reached = true;
	}

	public void render(PGraphics _g)
	{
		if (reached)
		{
			long currTime = new Date().getTime();
			colorFade = 1.0f - ((float) Math.min(currTime - startTime, fadeDur) / (float) fadeDur);
		}

		_g.fill(255.0f, 10.0f * colorFade);
		_g.noStroke();
		_g.strokeWeight(2 * getRadius());
		_g.beginShape(PConstants.TRIANGLE_STRIP);

		Vec2D p = null;
		Vec2D pr = null;
		Vec2D lv = null;
		Vec2D rv = null;

		for (int i = 0; i < getPoints().size(); i++)
		{
			p = getPoints().get(i);

			if (pr != null)
			{
				lv = p.sub(pr).normalize().rotate(-1.0f * MathUtils.HALF_PI).scaleSelf(getRadius()).addSelf(p);
				rv = p.sub(pr).normalize().rotate(MathUtils.HALF_PI).scaleSelf(getRadius()).addSelf(p);
			}
			else
			{
				if (getPoints().size() > 1)
				{
					Vec2D nx = getPoints().get(i + 1);
					lv = nx.sub(p).normalize().rotate(-1.0f * MathUtils.HALF_PI).scaleSelf(getRadius()).addSelf(p);
					rv = nx.sub(p).normalize().rotate(MathUtils.HALF_PI).scaleSelf(getRadius()).addSelf(p);
				}
				else
				{
					lv = Vec2D.fromTheta(0).rotate(-1.0f * MathUtils.HALF_PI).scaleSelf(getRadius()).addSelf(p);
					rv = Vec2D.fromTheta(0).rotate(MathUtils.HALF_PI).scaleSelf(getRadius()).addSelf(p);
				}
			}

			_g.vertex(lv.x, lv.y);
			_g.vertex(rv.x, rv.y);

			pr = p;
		}

		_g.endShape();
	}
}
